<?php
	function searchProducts($searchTerm, $itemsPerPage = 5)
	{
		if(getRequestParameter('p') != false)
		{
			$page = getRequestParameter('p');
		}
		else
		{
			$page = 1;
		}
		
		global $connection;
		
		$params[] = $_SESSION["language"]["id"];
		$params[] = "%".$searchTerm."%";
		$query = "SELECT 	p.*, pd.name, pd.url, pd.description, s.id AS stock_id, s.price, s.quantity, s.buy_count, s.has_image, 
							c.parent_id AS parent_category_id, c.id AS category_id FROM stocks s 
				      	LEFT JOIN products_details pd ON s.product_id = pd.product_id
				      	LEFT JOIN products p ON p.id = pd.product_id
				      	LEFT JOIN products_categories pc ON p.id = pc.product_id 
				      	LEFT JOIN categories c ON c.id = pc.category_id
				  WHERE pd.language_id = ? AND p.visible = 1 AND pd.name LIKE ?  GROUP BY p.id ORDER BY pd.name";
		
		
		$num_rows = $connection->num_rows($query, $params);
		
		if($itemsPerPage > 0)
		{
			$query .= " LIMIT ". ($page-1) * $itemsPerPage .", ".$itemsPerPage;
		}
		
		$products = $connection->fetch_result($query, $params);
		
		foreach($products as $key => $product) 
		{
			$products[$key]["num_rows"] = $num_rows;
			getProductDetails($products[$key]);
			
		}
		
		return $products;
		
	}



	/* Filter products for listing by:
	 *  - $categoryID  -> product category (if it's false, get from all categories)
	 *  - $type -> product type -> false = all, 0 = normal product, 1 = new product, 2 = comming soon, 3 = liquvidation, , 4 = discount/promotion, 5 = popular
	 *  - $filters -> array of product properties composed by {property name} : {property #ID}
	 *  - $itemsPerPage -> how many products to get
	 *  - $orderBy -> field to order by (can be 'id', 'name', 'price', 'buy_count', 'view_count')
	 *  - $sortOrder -> sort order => 'asc' or 'desc'
	 *  - $priceFilter -> numeric values separeted by "-", the first can be "gt" (greater then the second)
	 * */
	function filter_products($categoryID = false, $type = false, $filters = null, $itemsPerPage = 20, $orderBy = "id", $sortOrder = "asc", $priceFilter = 0, $parentCategoryID = false, $shopID = false)
	{
		
		if(getRequestParameter('p') != false)
		{
			$page = getRequestParameter('p');
		}
		else
		{
			$page = 1;
		}
		
		global $connection;
		
		$params[] = $_SESSION["language"]["id"];
		
		$query = "SELECT p.*, pd.name, pd.url, pd.description, pd.language_id, s.id AS stock_id, s.price, s.quantity, s.buy_count, s.has_image, 
						c.parent_id AS parent_category_id, c.id AS category_id,
						(SELECT COUNT(pv.product_id) FROM product_views pv WHERE pv.id = s.product_id) AS view_count 
						FROM stocks s 
				      	LEFT JOIN products_details pd ON s.product_id = pd.product_id
				      	LEFT JOIN products p ON p.id = pd.product_id
				      	LEFT JOIN products_categories pc ON p.id = pc.product_id 
				      	LEFT JOIN categories c ON c.id = pc.category_id
				  WHERE pd.language_id = ? AND p.visible = 1";
		if($categoryID != false)
		{
			$params[] = $categoryID;
			
			$query .= " AND c.id = ?";
		}
		if($parentCategoryID != false)
		{
			$params[] = $parentCategoryID;
			
			$query .= " AND c.parent_id = ?";
		}
		
		if($shopID != false)
		{
			$params[] = $shopID;
			
			$query .= " AND p.shop_id = ?";
		}
		
		if($type != false)
		{
			if($type == 1 || $type == 2)
			{
				$query .= " AND p.type = ?";
				$params[] = $type;
			}
			elseif($type == 3)
			{
				$query .= " AND p.has_liqvidation = 1";
			}
			elseif($type == 4)
			{
				$query .= " AND p.has_discount = 1";
			}
			elseif($type == 5)
			{
				$orderBy = "buy_count";
			}
		}
		
		if(count($filters) > 0)
		{
			foreach($filters as $filter)
			{
				$params[] = '%"'.$filter["property_id"].'":'.$filter["property_value_id"].'%';
				$query .= " AND s.properties LIKE ?";
			}
			
		}
		
		if($priceFilter != 0)
		{
			$priceFilter = get_price_filter($priceFilter);
			if(isset($priceFilter["id"]))
			{
				if($priceFilter["type"] == 1)
				{
					$query .= " AND s.price < ".$priceFilter["price1"];
				}
				elseif($priceFilter["type"] == 2)
				{
					$query .= " AND s.price > ".$priceFilter["price1"];
				}
				else
				{
					$query .= " AND s.price BETWEEN ".$priceFilter["price1"] ." AND ".$priceFilter["price2"];
				}
			}
		}
		
		$query .= " GROUP BY p.id";
		
		if($orderBy != "" || $sortOrder != "")
		{
			if($sortOrder == "desc")
			{
				$sortOrder = "desc";
			}
			else
			{
				$sortOrder = "asc";
			}
			
			if($orderBy == "price" || $orderBy == "buy_count")
			{
				$query .= " ORDER BY s.{$orderBy} {$sortOrder}";
			}
			elseif($orderBy == "id")
			{
				$query .= " ORDER BY p.{$orderBy} {$sortOrder}";
			}
			elseif($orderBy == "name")
			{
				$query .= " ORDER BY pd.{$orderBy} {$sortOrder}";
			}
			elseif($orderBy == "view_count")
			{
				$query .= " ORDER BY {$orderBy} {$sortOrder}";
			}
			else
			{
				$query .= " ORDER BY p.id {$sortOrder}";
			}
		}
		$num_rows = $connection->num_rows($query, $params);
		
		if($itemsPerPage > 0)
		{
			$query .= " LIMIT ". ($page-1) * $itemsPerPage .", ".$itemsPerPage;
		}
		
		$products = $connection->fetch_result($query, $params);
		
		foreach($products as $key => $product) 
		{
			$products[$key]["num_rows"] = $num_rows;
			getProductDetails($products[$key]);
			
		}
		
		return $products;
	}

	function getProductByField($fieldValue, $field = "url", $categoryID = null, $subCategoryID = null)
	{
		global $connection;
		
		if(!is_array($fieldValue))
		{
			$single = true;
			$fieldValues[] = $fieldValue;
		}
		else
		{
			$single = false;
			$fieldValues = $fieldValue;
		}
		$params[] = $_SESSION["language"]["id"];
		
		$query = "SELECT 	p.*, pd.name, pd.language_id, pd.url, s.id AS stock_id, s.price, s.quantity, s.buy_count, s.has_image, 
							c.id AS category_id, c.parent_id AS parent_category_id, pd.meta_description, pd.meta_keywords, pd.description
						FROM stocks s
				      	LEFT JOIN products_details pd ON s.product_id = pd.product_id
				      	LEFT JOIN products p ON p.id = pd.product_id
				      	LEFT JOIN products_categories pc ON p.id = pc.product_id
				      	LEFT JOIN categories c ON c.id = pc.category_id
				  WHERE pd.language_id = ? AND p.visible = 1";
		if($categoryID != null && $subCategoryID == null)
		{
			$params[] = $categoryID;
			$query .= " AND c.id = ?";
		}
		elseif($categoryID != null && $subCategoryID != null)
		{
			$params[] = $subCategoryID;
			$params[] = $categoryID;
			$query .= " AND c.id = ? AND c.parent_id = ?";
		}
		
		
		
		$stockID = null;
		
		foreach($fieldValues as $fieldValue)
		{
			if($field == "url")
			{
				$params[] = $fieldValue;
				$queryArray[] = " pd.url = ?";
			}
			elseif($field == "id")
			{
				$params[] = $fieldValue;
				$queryArray[] = " p.id = ?";
			}
			elseif($field == "stock_id")
			{
				$params[] = $fieldValue;
				$stockID = $fieldValue;
				$queryArray[] = " s.id = ?";
			}
		}
		
		$queryString = implode(" OR ", $queryArray);
		
		$query .= " AND ($queryString)";
		
		$query .= " GROUP BY p.id ";
		
		
		
		$products = $connection->fetch_result($query, $params);
		
		foreach($products as $key => $product)
		{
			if(isset($product["id"]))
			{
				getProductDetails($products[$key], $stockID);
			}
		}
		
		if($single == true)
		{
			return $products[0];
		}
		return $products;
		
	}
	
	// getRecommendedProducts($product)
	// - $product -> product object
	// First it checks if the current product has associated products, if not checks for 
	//	associated products for subcategory and lastly for category
	
	function getRecommendedProducts($product, $exception = null)
	{
		global $connection;
		
		$found = false;
		
		$params = array();
		$params[] = $product["id"];
		
		$query = "SELECT * FROM recommendations WHERE px_product_id = ?";
		$check = $connection->fetch_result($query, $params);
		
		if ($check) { $found = $check; }

		if (!$found && isset($product['category']["id"])) 
		{
			$params = array();
			$params[] = $product["category"]["id"];
			$query = "SELECT * FROM recommendations WHERE px_category_id = ?";
			$check = $connection->fetch_result($query, $params);
			if ($check) { $found = $check; }
		}

		if (!$found && $product['parent_category']["id"]) 
		{
			$params = array();
			$params[] = $product["parent_category"]["id"];
			$query = "SELECT * FROM recommendations WHERE px_category_id = ?";
			$check = $connection->fetch_result($query, $params);
			if ($check) { $found = $check; }

		}
		
		if ($found) 
		{
			$products = array();
			foreach($found as $key => $value)
			{
				if ($value['ry_product_id']) 
				{
					$products[] = getProductByField($value['ry_product_id'], "id");
				} 
				else 
				{
					$products = filter_products($value['ry_category_id'],false, null, 4);
				}
			}

		} 
		else 
		{
			// get most bought products by category or parent category
			$products = filter_products($product["category"]["id"], false, null, 4, "buy_count");
			
			if(count($products) == 0)
			{
				$products = filter_products(false, false, null, 4, "buy_count", "asc", false, $product["parent_category"]["id"]);
			}
		}
		
		if($exception != null)
		{
			foreach($products as $key => $product)
			{
				if($product["id"] == $exception)
				{
					unset($products[$key]);
				}
			}
		}
		
		return $products;
	}

	function getProductDetails(&$product, $stockID = null)
	{
		global $connection;
		
		if($stockID == null)
		{
			$pictureStockID = $product["stock_id"];
		}
		else
		{
			$pictureStockID = $stockID;
		}
		
		$product["images"] = getProductPictures($product["id"], $pictureStockID);
		
		$product["company"] = $company = getCompanyByField($product["shop_id"]);
		
		$params[] = $product["id"];
		$params[] = $product["language_id"];
		$categories = $connection->fetch_result("SELECT cd.*, c.parent_id, c.id, c.level FROM categories c 
												LEFT JOIN category_details cd ON c.id = cd.category_id
												WHERE c.id IN (SELECT category_id AS id FROM products_categories WHERE product_id = ?) AND cd.language_id = ?", $params);
		$level = 0;
		$bestCat = false;
		foreach($categories as $category)
		{
			$categoryURL = "";
			makeCategoryURL($category["id"], $categoryURL);
			
			$category["url"] = $categoryURL;
			if($level == 1)
			{
				$product["super_category"] = $category;
			}
			elseif($level == 2)
			{
				$product["parent_category"] = $category;
			}
			elseif($level == 3)
			{
				$product["category"] = $category;
			}
			
			if($category["level"] > $level)
			{
				$bestCat = $category;
				$level = $category["level"];
			}
		}
		
		$productURL = site_url();
		$productURL .= $company["url"]."/";
		$productURL .= $bestCat["url"];
		
		$product["url"] = $productURL.$product["url"].".html";
		
		$product["discount"] = $discount = getDiscount($product, @$_SESSION["client"]["id"]);
		
		$stocks  = getProductStocks($product["id"], $stockID);
		
		$priceMin = 0;
		$priceMax = 0;
		$totalStock = 0;
		
		foreach($stocks as $key => $stock) 
		{
			$stock["price"] = $stock["price"]+0;
			if($priceMin == 0 || $stock["price"] < $priceMin)
			{
				$priceMin = $stock["price"];
			}
			
			if($priceMax == 0 || $stock["price"] > $priceMax)
			{
				$priceMax = $stock["price"];
			}
			$totalStock += $stock["quantity"];
		}
		
		$currency = get_setting("currency");
		
		if($priceMax != $priceMin)
		{
			
			$product["old_price"] =  makePriceInterval($priceMin, $priceMax, $currency);
			
			$product["min_price_old"] = $priceMin;
			$product["max_price_old"] = $priceMax;
			
			$priceMax -= ($discount['discount_percent'] * $priceMax/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMax/100) : $discount['discount_static'];
			$priceMin -= ($discount['discount_percent'] * $priceMin/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMin/100) : $discount['discount_static'];
			
			$product["price"] = makePriceInterval($priceMin, $priceMax, $currency);
			
			$product["min_price"] = $priceMin;
			$product["max_price"] = $priceMax;
		}
		else
		{
			$product["old_price"] =  makePriceInterval($priceMin, 0,$currency);
			
			$product["min_price_old"] = $product["max_price_old"] = $priceMin;
			
			$priceMin -= ($discount['discount_percent'] * $priceMin/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMin/100) : $discount['discount_static'];
			
			$product["price"] =  makePriceInterval($priceMin, 0,$currency);
			
			$product["min_price"] = $product["max_price"] = $priceMin;
		}
		
		$product["total_stock"] = $totalStock;
		$product["properties"] = get_category_properties(null, $product["id"], $stockID);
	}

	function makeProductURL($product)
	{
		global $connection;
		$productURL = site_url();
		
		$category = $connection->fetch_one("SELECT cd.url, c.parent_id FROM categories c 
															LEFT JOIN category_details cd ON c.id = cd.category_id 
													WHERE c.id = ? AND cd.language_id = ?", array($product["category_id"], $_SESSION["language"]["id"]));
		if($category["parent_id"] > 0)
		{
			$parentCategory = $connection->fetch_one("SELECT cd.url, c.parent_id FROM categories c 
															LEFT JOIN category_details cd ON c.id = cd.category_id 
													WHERE c.id = ? AND cd.language_id = ?", array($category["parent_id"], $_SESSION["language"]["id"]));
			$productURL .= $parentCategory["url"]."/";
			
		}
		
		$productURL .= $category["url"]."/".$product["url"].".html";
		
		return $productURL;
	}
	
	function getProductStocks($productID, $stockID = null)
	{
		
		global $connection;
		$params[] = $productID;
		$query = "SELECT s.* FROM stocks s WHERE s.product_id = ? ";
		if($stockID != null)
		{
			$params[] = $stockID;
			$query .= " AND s.id = ?";
			
		}
		$query .= " ORDER BY s.price";
		$stocks = $connection->fetch_result($query, $params);
		return $stocks;
	}
	
	function getProductPictures($productID, $stockID = null)
	{
		global $connection;
		
		$params[] = $productID;
		
		$query = "SELECT pf.*, sp.main_picture, sp.stock_id, s.product_id, s.quantity
					FROM picture_files pf, stock_pictures sp, stocks s
					WHERE sp.picture_id = pf.id
					AND s.product_id = ? AND sp.stock_id = s.id ";
		if($stockID != null)
		{
			$params[] = $stockID;
			$query .= " AND s.id = ?";
		}
		$query .= " ORDER BY sp.main_picture DESC";
		
		$photos = $connection->fetch_result($query, $params);
		
		return $photos;
	}
	
	function getDiscount($product, $clientID = false, $debug = false)
	{
		global $connection;
		
		$productID = $product['id'];
		
		$superCategoryID = 0;
		if(isset($product["super_category"]["id"]))
		{
			$superCategoryID = $product["super_category"]["id"];
		}
		
		$parentCategoryID = 0;
		if(isset($product["parent_category"]["id"]))
		{
			$parentCategoryID = $product["parent_category"]["id"];
		}
		
		$categoryID = 0;
		
		if(isset($product["category"]["id"]))
		{
			$categoryID = $product["category"]["id"];
		}
		
		$price = $product['price'];
		
		$percent_cumulativ = 0;
		$percent_single = 0;
		
		$flat_cumulativ = 0;
		$flat_single = 0;
		
		if ( $clientID )
		{
			$params = array($clientID, $productID);
			
			$query = "SELECT * FROM discounts 
				WHERE ((coupon_code = '' OR coupon_code IS NULL) AND client_id = ? AND start < ".time()."  AND end > ".time()." ) 
				OR ((coupon_code = '' OR coupon_code IS NULL) AND product_id = ? AND start < ".time()."  AND end > ".time()." ) ";
			
			if($superCategoryID != 0)
			{
				$categoryArray[] = $superCategoryID;
			}
			if($parentCategoryID != 0)
			{
				$categoryArray[] = $parentCategoryID;
			}
			if($categoryID != 0)
			{
				$categoryArray[] = $parentCategoryID;
			}
			
			$categoryString = implode(",", $categoryArray);
			
			$query .= " OR ((coupon_code = '' OR coupon_code IS NULL) AND category_id IN ( $categoryString ) AND start < ".time()."  AND end > ".time()." )";
			
		}
		else
		{
			$params = array($productID);
			$query = "SELECT * FROM discounts 
				WHERE ( ((coupon_code = '' OR coupon_code IS NULL) AND product_id = ? AND start < ".time()."  AND end > ".time().") ";
			
			if($superCategoryID != 0)
			{
				$categoryArray[] = $superCategoryID;
			}
			if($parentCategoryID != 0)
			{
				$categoryArray[] = $parentCategoryID;
			}
			if($categoryID != 0)
			{
				$categoryArray[] = $parentCategoryID;
			}
			
			$categoryString = implode(",", $categoryArray);
			
			$query .= " OR ((coupon_code = '' OR coupon_code IS NULL) AND category_id IN ( $categoryString ) AND start < ".time()."  AND end > ".time()." )";
			
			$query .= ") ";
		}
		
		$params[] = $product["shop_id"];
		
		$query.= " AND company_id = ? ";
		
	
		$discounts = $connection->fetch_result($query, $params);
		foreach($discounts as $discount)
		{
			$found = false;
			
			if ($clientID and $discount['client_id'] == $clientID and !$discount['category_id'] and !$discount['product_id'])
			{
				$found = true;	
			}
			
			if (in_array($discount['category_id'],$categoryArray) and !$discount['client_id'] and !$discount['product_id'] )
			{
				$found = true; 
			}
			
			if ( $clientID and $discount['product_id'] == $productID and $discount['client_id'] == $clientID and !$discount['category_id'] ){ $found = true; }
			if ( $discount['product_id'] == $productID and (in_array($discount['category_id'],$categoryArray) OR !$discount["category_id"]) and !$discount['client_id'] ){ $found = true; }
			if ( $clientID and in_array($discount['category_id'],$categoryArray) and $discount['client_id'] == $clientID and !$discount['product_id'] ){ $found = true; }
			if ( $clientID and in_array($discount['category_id'],$categoryArray) and $discount['client_id'] == $clientID and $discount['product_id'] == $productID){  $found = true; }
				
			if ( $found )
			{
				if ( $discount['cumulative'] == 1 ){ 
					if ( $discount['type'] == 0 )
					{
						$percent_cumulativ += $discount['discount']; 
					}
					else
					{
						$flat_cumulativ += $discount['discount']; 
					}
				} else {
					if ( $discount['type'] == 0 )
					{
						if ( $percent_single < $discount['discount'] ){ $percent_single = $discount['discount']; }
					}
					else
					{
						if ( $flat_single < $discount['discount'] ){ $flat_single = $discount['discount']; }
					}
					
					
				}
			}
		}
		
		$data['original_price'] = $price;
		$data['discount_percent'] = $percent_cumulativ > $percent_single ? $percent_cumulativ : $percent_single;
		$data['discount_static'] = $flat_cumulativ > $flat_single ? $flat_cumulativ : $flat_single;
		$data['discount'] = ($data['discount_percent'] * $price/100) > $data['discount_static'] ? ($data['discount_percent'] * $price/100) : $data['discount_static'];
		
		if ( $debug )
		{
			echo "<pre>";
			echo "Pret: ".$price."<br>";
			echo "Percent cumulativ: ".$percent_cumulativ." > " .$price * $percent_cumulativ / 100 ."<br>";
			echo "Flat cumulativ: ".$flat_cumulativ."<br>";
			echo "Percent single: ".$percent_single." > " .$price * ($percent_single/100) ."<br>";
			echo "Flat single: ".$flat_single."<br>";
			echo "</pre>";
			
			echo "<pre>";
			print_r($data);
			echo"</pre>";
		}
		
		return $data;
	}

	function makePriceInterval($minValue, $maxValue = 0, $currency = null)
	{
		$minFloorValue = (int)$minValue;
		$minFractionalValue = $minValue - $minFloorValue;
		
		if($minFractionalValue == 0)
		{
			$minFractionalValue = "00";
		}
		else
		{
			$minFractionalValue = number_format($minFractionalValue+0, 2, ".",",");
			$minFractionalValue *= 100;
		}
		
		if(strlen($minFractionalValue) == 1)
		{
			$minFractionalValue .= "0";
		}
		
		$string = "<span>{$minFloorValue}<sup>.{$minFractionalValue}</sup>";
		
		if($maxValue != 0)
		{
			$string .= "</sup>";
			
			$maxFloorValue = (int)$maxValue;
			
			
			$maxFractionalValue = $maxValue - $maxFloorValue;
			if($maxFractionalValue == 0)
			{
				$maxFractionalValue = "00";
			}
			else
			{
				$maxFractionalValue = number_format($maxFractionalValue+0, 2, ".",",");
				$maxFractionalValue *= 100;
			}
			
			if(strlen($maxFractionalValue) == 1)
			{
				$maxFractionalValue .= "0";
			}
			
			$string .= "-$maxFloorValue<sup>.{$maxFractionalValue}";
		}
		
		
		$string .= "</sup></span>{$currency}";
		
		return $string;
	}
	
	function getPropertyList($properties)
	{
		foreach($properties as $key => $property):?>
			<ul class="filterList">
				<li class="listTitle"><?php echo $property["name"]; ?></li>
				<?php 
					$addClass = "";
					if($property["type"] == 2)
					{
						$addClass="colors";
					}
				?>
				<li class="<?php echo $addClass; ?> properties" property_id="<?php echo $key; ?>">
					<?php foreach($property["values"] as $k => $value): ?>
						
						<?php 
							$addStyle = "";
							if($property["type"] == 2)
							{
								$addStyle="background-color:#".$value["value"];
							}
						?>
						<a class="property" style="<?php echo $addStyle; ?>" href="#" title="<?php echo $value["name"]; ?>" property_value_id="<?php echo $k; ?>"><?php echo $value["name"]; ?></a>
						
					<?php endforeach; ?>
					<?php if($property["type"] == 5): ?>
						<li>
							<?php
								$sizeAssistPage = get_site_page_by_slug("size-assistance", $_SESSION["language"]["id"]);
							?>
							<a class="lowercase" target="_blank" href="<?php echo site_url() . $sizeAssistPage["url"];?>.html" 
								title="<?php echo $sizeAssistPage["name"];?>">
									<?php echo $sizeAssistPage["name"];?>
							</a>
						</li>
					<?php endif; ?>
				</li>
				<li class="error hidden"></li>
			</ul>
		<?php endforeach;
	}

	function getPossibleStocks($product, $selectedValues = array())
	{
		$params[] = $product["id"];
		
		$query = "SELECT s.id AS stock_id, s.properties, s.price, s.quantity FROM stocks s
					LEFT JOIN products p ON s.product_id = p.id  
					WHERE s.product_id = ? AND p.visible = 1 ";
		
		$valueIndex = 0;
		foreach($selectedValues as $value)
		{
			if($value["property_value_id"] > 0 && $value["property_id"] > 0)
			{
				$params[] = '%"'.$value["property_id"].'":'.$value["property_value_id"].'%';
				$query .= " AND s.properties LIKE ? ";
			}
			
		}
		
		global $connection;
		
		$stocks = $connection->fetch_result($query, $params);
		
		$discount = getDiscount($product, @$_SESSION["client"]["id"]);
		
		$possibleStocks = array();
		
		$priceMin = 0;
		$priceMax = 0;
		$totalStock = 0;
		
		foreach($stocks as $key => $stock)
		{
			if($stock["quantity"] > 0)
			{
				if($stock["properties"] != "")
				{
					$properties = json_decode($stock["properties"], true);
					
					if($priceMin == 0 || $stock["price"] < $priceMin)
					{
						$priceMin = $stock["price"];
					}
					
					if($priceMax == 0 || $stock["price"] > $priceMax)
					{
						$priceMax = $stock["price"];
					}
					$totalStock += $stock["quantity"];
					$valueCount = 0;
					foreach($properties as $key => $value)
					{
						$possibleStocks["property_values"][$value] = $key;
						$valueCount++;
					}
				}
			}
			else
			{
				unset($stocks[$key]);
			}
		}
		$currency = get_setting("currency");
		
		if($priceMax != $priceMin)
		{
			$possibleStocks["old_price"] =  makePriceInterval($priceMin, $priceMax, $currency);
			
			$priceMax -= ($discount['discount_percent'] * $priceMax/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMax/100) : $discount['discount_static'];
			$priceMin -= ($discount['discount_percent'] * $priceMin/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMin/100) : $discount['discount_static'];
			
			$possibleStocks["price"] = makePriceInterval($priceMin, $priceMax, $currency);
		}
		else
		{
			$possibleStocks["old_price"] =  makePriceInterval($priceMin, 0,$currency);
			$priceMin -= ($discount['discount_percent'] * $priceMin/100) > $discount['discount_static'] ? ($discount['discount_percent'] * $priceMin/100) : $discount['discount_static'];
			$possibleStocks["price"] =  makePriceInterval($priceMin, 0,$currency);
		}
		
		if(count($stocks) == 1)
		{
			$possibleStocks["stock_id"] = $stocks[0]["stock_id"];
			$possibleStocks["quantity"] = $totalStock;
			
			if($totalStock == 0)
			{
				$possibleStocks["stock_text"] = translate("no_stock");
			}
			elseif($totalStock <= 5)
			{
				$possibleStocks["stock_text"] = translate("limited_stock");
			}
			else
			{
				$possibleStocks["stock_text"] = translate("on_stock");
			}
		}
		
		return $possibleStocks;
		
	}

	function get_product_stocks($productID)
	{
		global $connection;
		
		$stocks = $connection->fetch_result("SELECT * FROM stocks WHERE product_id = ?", array($productID));
		
		foreach($stocks as $stock)
		{
			$stock["images"] = getProductPictures($productID, $stock["id"]);
		}
		
		return $stocks;
	}

	function get_price_filters()
	{
		global $connection;
		
		$priceFilters = $connection->fetch_result("SELECT * FROM price_filters ORDER BY price1");
		
		return $priceFilters;
		
	}
	
	function get_price_filter($id)
	{
		global $connection;
		
		$priceFilter = $connection->fetch_row("price_filters", $id);
		
		return $priceFilter;
	}
	
	function getWholesaleTable($product, $quantity = 1)
	{
		global $connection;
		
		$wholesales = $connection->fetch_result("SELECT * FROM stocks_wholesale WHERE stock_id = ?", array($product["stock_id"]));
		
		if($wholesales)
		{
			include("html-includes/product/items/wholesale-table.php");
		}
	}
?>